/**
 * 创建一个HTTP 服务，端口 9000， 需求；
 * GET /index.html      响应 page/index/html 文件内容
 * GET /css/app.css      响应 page/css/app.css 文件内容
 * GET /image/logo.png      响应 page/image/logo.png 文件内容
 * **/

const http = require('http');
const fs = require('fs');
const path = require('path');
// 静态资源类型声明
const mimes = {
  'png': 'image/png',
  'js': 'application/javascript',
  'html': 'text/html',
  'css': 'text/css'
}

const server = http.createServer((request, response) => {
  if (response.method !== 'GET') {
    response.statuCode = 405;
    response.end(`<h1>405 Method Not Allowed</h1>`);
    return
  }

  let { pathname } = new URL(request.url, 'http://127.0.0.1');
  // 声明变量 静态文件路径常量
  // let root = __dirname + '/../';
  let root = __dirname + '/page/';

  // 拼接文件路径
  let filePath = root + pathname;
  console.log(filePath)
  // 读取文件 fs 异步 api
  fs.readFile(filePath, (err, data) => {
    response.setHeader('content-type', 'text/html;charset=utf-8');

    if (err) {
      switch (err.code) {
        case 'ENOENT'://文件找不到
          response.statuCode = 404;
          response.end(`<h1>404 Not Found</h1>`);
          break;
        case 'EPERM'://禁止访问
          response.statuCode = 403;
          response.end(`<h1>403 Not Forbidden</h1>`);
          break;
        default:
          response.statuCode = 500;
          response.end(`<h1>500 Internal Server Error</h1>`);
          break;
      }
      console.log(err)
      return false;
    }
    // 获取文件后缀名
    let ext = path.extname(filePath).slice(1);
    console.log(ext);
    // 判断是否有文件类型
    if (mimes[ext]) {
      if (ext === 'html') {
        response.setHeader('content-type', mimes[ext] + ';charset=utf-8')
      } else {
        response.setHeader('content-type', mimes[ext])
      }
    } else {
      response.setHeader('content-type', 'application/octet-stream');
    }

    response.end(data);
  })

})


server.listen(9000, () => {
  console.log('服务启动中...')
})